package cn.summit;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author summit
 * @since 2021/8/11 23:15
 */
public class 两数之和 {

	public static void main(String[] args) {
		//violence();
		int[] a = { 6, 2, 7, 11, 15 };
		int sum = 13;
		int[] ints = twoSum(a, 26);
		System.out.println(ints);

		int[] v = { 2, 7, 11, 15 };

		System.out.println("---------------------");
		int[] ints1 = hashJie(v, 9);
		System.out.println(Arrays.toString(ints1));
	}

	public static int[] twoSum(int[] nums, int target) {
		int[] a = new int[2];
		int index = -1;
		for (int i = 0; i < nums.length; i++) {
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[i] + nums[j] == target) {
					a[++index] = nums[i];
					a[++index] = nums[j];
				}
			}

		}
		return a;
	}

	public static int[] hashJie(int[] nums, int target) {
		int[] res = new int[2];
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			int cha = target - nums[i];
			if (map.get(cha) != null) {
				return new int[] { nums[i], nums[map.get(cha)] };
			}
			map.put(nums[i], i);
		}
		return res;
	}

	/**
	 * 暴力法
	 * 时间复杂度 O(n^2)
	 */
	public static void violence() {

		Integer[] a1 = {};
		Integer[] a = { 6, 2, 7, 11, 15 };
		Integer sum = 13;

		for (int i = 0; i < a.length; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[i] + a[j] == sum) {
					System.out.println("下标为：" + i + ",值：" + a[i]);
					System.out.println("下标为：" + j + ",值：" + a[j]);
					System.out.println("结果为：" + sum);
				}
			}
		}

	}
}
